package com.cskaoyan.controller;

import com.cskaoyan.aliyun.WdAliyunClient;
import com.cskaoyan.bean.data.OssPutResult;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.model.MarketStorage;
import com.cskaoyan.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RequestMapping("wx/storage")
@RestController
public class WxStorageController {
    @Autowired
    StorageService storageService;

    @Autowired
    WdAliyunClient aliyunClient;

    //文件上传
    @PostMapping("upload")
    public BaseRespVo upload(MultipartFile file) throws IOException {
        //获取上传文件原始的文件名
        String originalFilename = file.getOriginalFilename();
        //获得正文类型(文件类型)比如imag/jpeg
        String contentType = file.getContentType();
        //文件的字节大小
        long size = file.getSize();
        //随机生成一个字符串，因为UUID所生成的内容中间是有横杠的，所以需要替换掉
        String random = UUID.randomUUID().toString().replace("-", "");
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//获得其文件类型比如.jpeg
        String objectName = random + suffix;

        //通过阿里云上传文件
        OssPutResult result = aliyunClient.save(file);
        //通过返回值能够得到其访问路径
        String accessUrl = result.getUrl();

        //将所获得的数据封装成MarketStorage对象
        MarketStorage marketStorage =MarketStorage.builder()
                .key(objectName)
                .name(originalFilename)
                .type(contentType)
                .size((int) size)
                .url(accessUrl)
                .deleted(false)
                .build();
        //将文件上传的相关信息传入到数据库
        storageService.create(marketStorage);
        return BaseRespVo.ok(marketStorage);
    }
}
